
import axios from 'axios'
// import store from 'store2'

const isDev = process.env.NODE_ENV === 'development'
const instance = axios.create({
    baseURL: isDev ? 'https://elm.cangdu.org/v1/' : 'https://elm.cangdu.org/v1/',
    withCredentials: true,

})

// 请求拦截器的封装
instance.interceptors.request.use(config => {

    return config
})


// 响应拦截器的封装
instance.interceptors.response.use(response => {

    return response
})

// 后续借助这个request请求实现get/post相关的接口调用
export default function request(config) {
    const { url = '', method = 'GET', data = {}, headers = {} } = config
    switch (method.toUpperCase()) {
        case 'GET':
            return instance.get(url, { params: data })
        case 'POST':
            // 如果是表单提交
            if (headers['content-type'] === 'application/x-www-form-url-encoded') {
                const p = new URLSearchParams()
                for (const key in data) {
                    p.append(key, data[key])
                }
                return instance.post(url, p, { headers })
            }
            // 如果是文件提交
            if (headers['content-type'] === 'multipart/form-data') {
                const p = new FormData()
                for (const key in data) {
                    p.append(key, data[key])
                }
                return instance.post(url, p, { headers })
            }
            // 否则就是 application/json的形式
            return instance.post(url, data)
        default:
            return instance(config)
    }
}
